var express = require('express');
var router = express.Router();
const shsDB = require("../db/index.js");
const addOnlienUser = require('./../utils/online');

const {
	jwtVerify
} = require('../utils/token.js');
router.post("/userinfo", jwtVerify, function(req, res) {
	let obj = {
		code: 201,
		message: "Error",
		type: 0,
		data: {
			message: "未按要求传参", //业务消息
		},
		token: "",
	}
	try {
		let item = req.body
		if (!item.id) {
			res.send(JSON.stringify(obj))
			return;
		}
		let sql = `select * from users where Id='${ item.id}'`;
		shsDB(sql).then((data) => {
			try {
				if (data.length == 0) {
					obj.message = "Error:There is no such user ";
					throw new Error(JSON.stringify(obj))
				}
				let status = data[0].status; //判断是否是正常用户
				if (status) {
					obj.message = "获取成功";
					obj.data = data[0];
					delete obj.data.password; //删除password属性
				} else {
					obj.data = [];
					obj.message = "用户状态异常";
				}
				obj.code = 200;
				res.send(JSON.stringify(obj))
			} catch (e) {
				res.send(JSON.stringify(obj))
			}
		}).catch(err => {
			obj.message = err.message;
			res.send(JSON.stringify(obj))
		})

	} catch (e) {
		//TODO handle the exception
	}
})
//无参 token
router.post('/info', jwtVerify, function(req, res, next) {
	let obj = {
		code: 201,
		message: "Error:get new userinfo",
		type: 0,
		data: {
			message: "", //业务消息
		},
		token: "",
	}
	try {
		let userinfo = req.shsImUserInfo
		let sql =
			`select * from users where username='${userinfo.fromName}' and Id='${ userinfo.fromId}'`;
		shsDB(sql).then((data) => {
			try {
				if (data.length == 0) {
					obj.message = "Error:There is no such user ";
					throw new Error(JSON.stringify(obj))
				}
				let status = data[0].status; //判断是否是正常用户
				if (status) {
					obj.message = "获取成功";
					obj.data = data[0];
					obj.data.Integral += 50;
					delete obj.data.password; //删除password属性
					obj.token = userinfo.token;
					if (obj.data.url != userinfo.fromUrl || obj.data.username != userinfo.fromName) {
						obj.token = jwt.sign({
							fromId: obj.data.Id,
							fromUrl: obj.data.url,
							fromName: obj.data.username
						}, secretKey, {
							expiresIn: expiresIn
						})
					}

					if (wsClientUsers[data[0].Id] == undefined) {
						wsClientUsers[data[0].Id] = obj.data
						addOnlienUser(data[0].Id, req, "getInfo", 1)
					}
					obj.code = 200;
					res.send(JSON.stringify(obj))
				} else {
					obj.message = "Error:get user status  异常";
					throw new Error(JSON.stringify(obj))
				}
			} catch (e) {
				//TODO handle the exception
				res.json(obj);
			}
		}).catch(err => {
			obj.message = err.message;
			res.json(obj);
		})
	} catch (e) {
		//TODO handle the exception
		res.json(obj);
		return;
	}

})
router.post('/login', function(req, res, next) {
	let bodyItem = req.body;
	let obj = {
		code: 200,
		message: "请检查网络设置",
		type: 0,
		data: {
			message: "", //业务消息
		},
		token: "",
	}
	obj.username = bodyItem.username

	if (!bodyItem.username || !bodyItem.password) {
		obj.message = "未按要求传参";
		obj.code = 201;
		res.end(JSON.stringify(obj));
		return;
	}
	let selectSql = `select * from users where username='${bodyItem.username}'`;
	shsDB(selectSql).then(data => {
		if (data.length == 0) {
			obj.message = "未注册";
			throw new Error(JSON.stringify(obj))
		}
		let sql =
			`select * from users where username='${bodyItem.username}' and password='${bodyItem.password}'`;
		return shsDB(sql);
	}).then(data => {
		if (data.length == 0 || data[0].password != bodyItem.password) {
			obj.message = "密码错误";
			throw new Error(JSON.stringify(obj))
		}
		//看状态是否正常
		// status 状态0封禁1正常
		let status = data[0].status;
		if (status) {
			obj.message = "登录成功";
			obj.data = data[0];
			obj.data.Integral += 50;
			delete obj.data.password; //删除password属性
			obj.token = jwt.sign({
				fromId: obj.data.Id,
				fromUrl: obj.data.url,
				fromName: obj.data.username
			}, secretKey, {
				expiresIn: expiresIn
			})
			wsClientUsers[data[0].Id] = obj.data
			upIntegral(obj.data.Id, 50);
			addOnlienUser(data[0].Id, req, "login", 1)
			res.json(obj);
		} else {
			//登录失败
			obj.message = "账号异常";
			throw new Error(JSON.stringify(obj))
		}

	}).catch(err => {
		obj.code = 201;
		if (obj.message === '未注册' || obj.message === '密码错误' || obj.message === '账号异常') {
			res.json(obj);
			return;
		}
		obj.message = err.message
		res.json(obj);
		console.log('err错误', err.message, "obj错误", obj);
	})
});
// 注册
router.post('/register', function(req, res, next) {
	let bodyItem = req.body;
	let obj = {
		code: 201,
		message: "",
		data: {
			message: "", //业务消息
		}
	}
	if (!bodyItem.username || !bodyItem.password) {
		obj.message = "未按要求传参";
		obj.code = 201;
		res.end(JSON.stringify(obj));
		return;
	}
	try {
		let userName = bodyItem.username;
		let password = bodyItem.password;
		let gender = bodyItem.gender;
		let hobbylist = bodyItem.hobbylist
		let signature = bodyItem.signature

		let select = `select * from users where username='${userName}'`;
		shsDB(select).then(data => {
			if (data.length > 0) {
				obj.message = '该名称已被注册，换一个名称吧~';
				throw new Error(obj.message)
			}
			// let oldUtl= `http://${nowIP}:${port}/images/${gender}/${Number.parseInt(Math.random()*3+1)}.webp`;
			let url = `${imageNowIP}/images/${gender}/${Number.parseInt(Math.random()*3+1)}.webp`;
			let sql =
				`insert into users(Id,username,password,url,gender,isAdmin,status,Integral,createTime,updateTime,hobbylist,signature) 
			VALUES(null,'${userName}','${password}','${url}',${gender},0,1,0,NOW(),NOW(),'${hobbylist}','${signature}')`;
			return shsDB(sql);
		}).then(data => {
			obj.code = 200;
			obj.message = "注册成功";
			res.send(JSON.stringify(obj))
		}).catch(err => {
			if (err == "该名称已被注册，换一个名称吧~") {
				res.send(JSON.stringify(obj))
			} else {
				obj.message = err.message
				res.send(JSON.stringify(obj))
			}

		})
	} catch (e) {}
});
// 修改个人信息 加token
router.post('/update', jwtVerify, function(req, res, next) {
	let bodyItem = req.body;
	let obj = {
		code: 200,
		message: "",
		data: {
			message: "", //业务消息
		}
	}
	let userinfo = req.shsImUserInfo
	if (userinfo.fromId == undefined || !bodyItem.username || !bodyItem.url || bodyItem.gender ==
		undefined || typeof bodyItem.gender != typeof 1) {
		obj.message = "未按要求传参";
		obj.code = 201;
		res.end(JSON.stringify(obj));
		return;
	}
	let {
		Id,
		username,
		url,
		gender,
		password
	} = bodyItem;
	Id = userinfo.fromId;
	let select = `select * from users where username='${username}' and Id!=${Id}`;
	shsDB(select).then(data => {
		if (data.length > 0) {
			obj.message = '该名称已被使用，换一个名称吧~';
			throw new Error(JSON.stringify(obj))
		}
		let sql =
			`UPDATE \`users\` SET \`username\` = '${username}',\`url\` = '${url}',\`gender\` = '${gender}',\`updateTime\` =NOW() WHERE \`Id\` = '${Id}'`;
		return shsDB(sql);
	}).then(data => {
		obj.message = "修改成功";
		obj.data = bodyItem;
		obj.token = jwt.sign({
			fromId: Id,
			fromUrl: url,
			fromName: username
		}, secretKey, {
			expiresIn: expiresIn
		})
		wsClientUsers[Id] = {
			...wsClientUsers[Id],
			...obj.data
		}
		//重新推送
		let senddata = {
			type: 33,
			data: wsClientUsers[Id],
			Id: Id,
			status: true,
			message: "Update the standings"
		}
		let allSendDara = {
			type: 333,
			data: bodyItem,
			Id: Id,
			status: true,
			message: "all update userinfo"
		}
		//推送本身所有端
		if (wsClients[Id]) {
			wsClients[Id].forEach((client, index) => {
				if (client.wtoken == userinfo.token) {
					client.wtoken = obj.token
				} else {
					allSendDara.token = jwt.sign({
						fromId: Id,
						fromUrl: url,
						fromName: username,
						index
					}, secretKey, {
						expiresIn: expiresIn
					})
					client.wtoken = allSendDara.token
					client.shsImUserInfo = {
						fromId: Id,
						fromName: username,
						fromUrl: url,
						token: allSendDara.token
					}
					client.send(JSON.stringify(allSendDara))
				}
			})
		}
		WSsendAll(senddata) //积分 全推送
		res.json(obj);
	}).catch(err => {
		obj.code = 201;
		res.json(obj);
	})
});
/**
 * 修改信息 推送全端更新 不更新token
 * @param {object} bodyItem 用户信息
 */
function sendUserSelfData(Id, bodyItem) {
	let allSendDara = {
		type: 3333,
		data: bodyItem,
		Id: Id,
		status: true,
		message: "userinfo"
	}
	//推送本身所有端
	if (wsClients[Id]) {
		wsClients[Id].forEach((client, index) => {
			client.send(JSON.stringify(allSendDara))
		})
	}
}

// 修改个人信息 加token hobby
router.post('/update/hobby', jwtVerify, function(req, res, next) {
	let bodyItem = req.body;
	let obj = {
		code: 200,
		message: "",
		data: {
			message: "", //业务消息
		}
	}
	let userinfo = req.shsImUserInfo
	if (userinfo.fromId == undefined) {
		obj.message = "未按要求传参";
		obj.code = 201;
		res.end(JSON.stringify(obj));
		return;
	}

	let hobbys = bodyItem.hobbys || "";
	let Id = userinfo.fromId;
	let sql =
		`UPDATE \`users\` SET \`hobbylist\` = '${hobbys}',\`updateTime\` =NOW() WHERE \`Id\` = '${Id}'`;
	shsDB(sql).then(data => {
		obj.message = "修改成功";
		obj.data = bodyItem;
		sendUserSelfData(Id, {
			hobbylist: bodyItem.hobbys
		})
		res.json(obj);
	}).catch(err => {
		obj.code = 201;
		res.json(obj);
	})
});

// 修改个人信息 加token signature
router.post('/update/signature', jwtVerify, function(req, res, next) {
	let bodyItem = req.body;
	let obj = {
		code: 200,
		message: "",
		data: {
			message: "", //业务消息
		}
	}
	let Id = req.shsImUserInfo.fromId;
	if (Id == undefined) {
		obj.message = "未按要求传参";
		obj.code = 201;
		res.end(JSON.stringify(obj));
		return;
	}
	let signature = bodyItem.signature || "";

	let sql =
		`UPDATE \`users\` SET \`signature\` = '${signature}',\`updateTime\` =NOW() WHERE \`Id\` = '${Id}'`;
	shsDB(sql).then(data => {
		obj.message = "修改成功";
		obj.data = bodyItem;
		sendUserSelfData(Id, bodyItem)
		res.json(obj);
	}).catch(err => {
		obj.code = 201;
		res.json(obj);
	})
});
// 修改个人信息 加token 密码
router.post('/update/password', jwtVerify, function(req, res, next) {
	let bodyItem = req.body;
	let obj = {
		code: 200,
		message: "",
		data: {
			message: "", //业务消息
		}
	}
	let Id = req.shsImUserInfo.fromId;
	if (Id == undefined || !bodyItem.password || !bodyItem.oldpassword) {
		obj.message = "未按要求传参[password,oldpassword]";
		obj.code = 201;
		res.end(JSON.stringify(obj));
		return;
	}
	let {
		oldpassword,
		password
	} = bodyItem;

	let sql =
		`UPDATE \`users\` SET \`password\` = '${password}',\`updateTime\` =NOW() WHERE \`Id\` = '${Id}'`;
	shsDB(sql).then(data => {
		obj.message = "修改成功";
		obj.data = "";
		res.json(obj);
	}).catch(err => {
		obj.code = 201;
		res.json(obj);
	})
});


//退出登录
router.post("/logout", jwtVerify, function(req, res, next) {
	let userinfo = req.shsImUserInfo
	let send = {
		code: 200,
		message: "用户状态消息",
		type: 3,
		data: wsClientUsers,
		userCount: userCount,
		status: 0,
		Id: userinfo.fromId,
		username: userinfo.fromName,
		onlineTime: getdate()
	}
	let sendObj = {
		code: 200,
		message: "退出成功",
		status: true
	}
	res.send(JSON.stringify(sendObj))
})

function handledUpdate(obj, Id) {
	wsClientUsers[Id] = {
		...wsClientUsers[Id],
		...obj.data
	}
	//重新推送
	let senddata = {
		type: 33,
		data: wsClientUsers[Id],
		Id: Id,
		status: true,
		message: "Update the standings"
	}
	WSsendAll(senddata) //积分 全推送
}

//用户封禁 发布的所有动态也封禁 操作者id：fromId  ；被封禁者id:bannedId;备注 remark  状态 1启用0禁用 3待审核4未通过5删除
router.post("/banned", jwtVerify, function(req, res, next) {
	let bodyItem = req.body;
	let userinfo = req.shsImUserInfo; //看谁执行的封禁操作

	let obj = {
		code: 201,
		message: "封禁操作",
		status: true
	}

	if (!userinfo.fromId || !bodyItem.bannedId || bodyItem.status == undefined) {
		obj.message = "未按要求传参[fromId,bannedId]";
		obj.code = 201;
		res.end(JSON.stringify(obj));
		return;
	}
	if (bodyItem.bannedId == 1) {
		obj.message = "倒反天罡[管理员你也禁呀]";
		obj.code = 201;
		res.end(JSON.stringify(obj));
		return;
	}
	let remark = "封禁用户及动态"
	let oldStatus = '';
	try {
		oldStatus = bodyItem.status ? 0 : 1
		if (bodyItem.status) {
			remark = "解除封禁用户及动态"
		}
	} catch (error) {
		//TODO handle the exception
	}
	// 封禁用户表的用户status
	// 封禁动态表的发布信息
	let userSql =
		`UPDATE \`imdb\`.\`users\` SET  \`status\` = ${ bodyItem.status},updateTime=now() WHERE \`Id\` = ${bodyItem.bannedId};`
	let stateSql =
		`UPDATE \`imdb\`.\`statecontent\` SET  \`status\` = ${ bodyItem.status},updateTime=now() WHERE \`fromId\` = ${bodyItem.bannedId} and status=${oldStatus} ;`
	let controlsSql =
		`INSERT INTO \`imdb\`.\`banned\`(\`id\`, \`controlsID\`, \`bannedId\`, \`remark\`, \`status\`, \`updateTime\`, \`createTime\`)
		 VALUES (null, ${userinfo.fromId}, ${bodyItem.bannedId}, '${remark }', 1, now(), now());`
	shsDB(userSql).then(data => {
		return shsDB(stateSql);
	}).then(data => {
		return shsDB(controlsSql)
	}).then(data => {
		obj.code = 200;
		obj.message = "操作成功"
		res.send(JSON.stringify(obj))
	}).catch(err => {
		obj.code = 201;
		res.send(JSON.stringify(obj))
	})

})
router.post("/setAdminStatus", jwtVerify, function(req, res, next) {
	let bodyItem = req.body; // 获取请求体中的数据
	let userinfo = req.shsImUserInfo; // 获取执行操作的用户信息

	let obj = {
		code: 201, // 默认返回码
		message: "设置管理员状态失败", // 默认消息
		status: false // 默认操作状态
	};

	// 参数校验
	if (!userinfo.fromId || !bodyItem.bannedId || bodyItem.isAdmin === undefined) {
		obj.message = "未按要求传参[fromId, bannedId, isAdmin]";
		res.end(JSON.stringify(obj));
		return;
	}

	// 封禁用户表的用户状态更新
	let userSql = `
        UPDATE \`imdb\`.\`users\` 
        SET \`isAdmin\` = ${bodyItem.isAdmin}, 
            \`updateTime\` = now() 
        WHERE \`Id\` = ${bodyItem.bannedId};
    `;

	// 记录操作日志
	let remark = bodyItem.isAdmin ? "设置为管理员" : "取消管理员权限";
	let controlsSql =
		`INSERT INTO \`imdb\`.\`banned\`(\`id\`, \`controlsID\`, \`bannedId\`, \`remark\`, \`status\`, \`updateTime\`, \`createTime\`)
		 VALUES (null, ${userinfo.fromId}, ${bodyItem.bannedId}, '${remark }', 1, now(), now());`

	// 执行数据库操作
	shsDB(userSql)
		.then(data => {
			return shsDB(controlsSql); // 记录操作日志
		})
		.then(data => {
			obj.code = 200; // 操作成功
			obj.message = "操作成功";
			obj.status = true;
			res.send(JSON.stringify(obj));
		})
		.catch(err => {
			obj.message = "数据库操作失败：" + err.message; // 捕获错误
			res.send(JSON.stringify(obj));
		});
});
//用户查询
router.post("/userinfoAll", jwtVerify, function(req, res) {
	let obj = {
		code: 201,
		message: "Error",
		type: 0,
		data: {
			message: "未按要求传参", //业务消息
		},
		token: "",
	}
	try {
		let item = req.body
		if (!item.id) {
			res.send(JSON.stringify(obj))
			return;
		}
		let sql = `select * from users where Id='${ item.id}'`;
		shsDB(sql).then((data) => {
			try {
				obj.message = "获取成功";
				if (data.length == 0) {
					obj.data = 0
					obj.message = "There is no such user ";
				} else {
					obj.data = data[0];
					delete obj.data.password; //删除password属性
				}
				obj.code = 200;
				res.send(JSON.stringify(obj))
			} catch (e) {
				res.send(JSON.stringify(obj))
			}
		}).catch(err => {
			obj.message = err.message;
			res.send(JSON.stringify(obj))
		})

	} catch (e) {
		//TODO handle the exception
	}
})

module.exports = router;